/**
 * 
 */
package edu.umd.clip.lm.storage.remote;

import java.util.concurrent.atomic.AtomicLong;

import edu.umd.clip.lm.model.OnDiskCompactProbTree;
import edu.umd.clip.lm.storage.*;
import edu.umd.clip.lm.storage.remote.ServerStorageConnection.Task;
/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class ServerStorageResponder {
	private final AbstractProbTreeStorage storage;
	private final ServerStorageConnection connection;
	private final static AtomicLong timeSpent = new AtomicLong();
	
	public ServerStorageResponder(AbstractProbTreeStorage storage, ServerStorageConnection connection) {
		this.storage = storage;
		this.connection = connection;
	}

	// NOTE: it assumes the storage is associated with the modelId in the task
	public boolean process(Task task) {
		if (task.message.getType() == Message.MessageHeader.SINGLE_TREE_REQUEST) {
			long start = System.nanoTime();
			SingleTreeRequestMessage message = (SingleTreeRequestMessage) task.message;
			OnDiskCompactProbTree probTree = storage.getProbTree(message.getModelId(), message.getClusterid(), message.getFactorBits());
			
			Message response;
			if (probTree == null) {
				response = new FailureResponseMessage(message.getModelId(), FailureResponseMessage.NOT_FOUND, "", message.getId());
			} else {
				//probTree = probTree.compact();
				//probTree.setTuple(message.getFactorBits());
				response = new SingleTreeResponseMessage(probTree, message.getModelId(), message.getId());
			}
			connection.postReply(task, response);
			long end = System.nanoTime();
			timeSpent.addAndGet(end - start);
			return true;
		}
		System.err.printf("received unkown message type %d\n", task.message.getType());
		return false;
	}
	
	public static long getTimeSpend() {
		return timeSpent.longValue();
	}
}
